<template>
    <div class="activity-manage">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>活动管理</h2>
      <el-button type="primary" @click="handleUpdateStatus" :loading="statusLoading">
        <el-icon>
          <Refresh />
        </el-icon>
        一键更新活动状态
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" inline>
        <el-form-item label="活动名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入活动名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch" :loading="loading">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          <el-button type="success" :icon="Plus" @click="handleAdd">新增活动</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="hover">
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="activityList"
          stripe
          border
          style="width: 100%"
          :height="tableHeight"
        >
        <el-table-column type="index" label="序号" width="60" align="center" />
        
        <el-table-column prop="aname" label="活动名称" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="activity-name">
              <el-text class="activity-title" type="primary">{{ row.aname }}</el-text>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="ename" label="发布人" width="120" align="center" />

        <el-table-column prop="activityStartTime" label="开始时间" width="120" align="center">
          <template #default="{ row }">
            {{ formatDate(row.activityStartTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="activityEndTime" label="结束时间" width="120" align="center">
          <template #default="{ row }">
            {{ formatDate(row.activityEndTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="signupStartTime" label="报名开始" width="120" align="center">
          <template #default="{ row }">
            {{ formatDate(row.signupStartTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="signupEndTime" label="报名截止" width="120" align="center">
          <template #default="{ row }">
            {{ formatDate(row.signupEndTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="status" label="活动状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="location" label="活动地点" min-width="120" show-overflow-tooltip />

        <el-table-column label="报名情况" width="120" align="center">
          <template #default="{ row }">
            <div class="participant-info">
              <el-text :type="row.currentParticipants >= row.capacity ? 'danger' : 'success'">
                {{ row.currentParticipants || 0 }} / {{ row.capacity || 0 }}
              </el-text>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            <div class="time-display">
              <span class="relative-time" :title="formatDateTime(row.createTime)">
                {{ formatRelativeTime(row.createTime) }}
              </span>
              <div class="exact-time">{{ formatDateTime(row.createTime) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="updateTime" label="修改时间" width="180" align="center">
          <template #default="{ row }">
            <div class="time-display">
              <span class="relative-time" :title="formatDateTime(row.updateTime)">
                {{ formatRelativeTime(row.updateTime) }}
              </span>
              <div class="exact-time">{{ formatDateTime(row.updateTime) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="View" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="warning" size="small" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[5, 10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 活动详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="活动详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentActivity" class="activity-detail">
        <div class="detail-grid">
          <div class="detail-item">
            <label>活动名称：</label>
            <span>{{ currentActivity.aname }}</span>
          </div>
          <div class="detail-item">
            <label>发布人：</label>
            <span>{{ currentActivity.ename }}</span>
          </div>
          <div class="detail-item">
            <label>活动状态：</label>
            <el-tag :type="getStatusType(currentActivity.status)">
              {{ getStatusText(currentActivity.status) }}
            </el-tag>
          </div>
          <div class="detail-item">
            <label>活动地点：</label>
            <span>{{ currentActivity.location }}</span>
          </div>
          <div class="detail-item">
            <label>活动开始时间：</label>
            <span>{{ formatDate(currentActivity.activityStartTime) }}</span>
          </div>
          <div class="detail-item">
            <label>活动结束时间：</label>
            <span>{{ formatDate(currentActivity.activityEndTime) }}</span>
          </div>
          <div class="detail-item">
            <label>报名开始时间：</label>
            <span>{{ formatDate(currentActivity.signupStartTime) }}</span>
          </div>
          <div class="detail-item">
            <label>报名截止时间：</label>
            <span>{{ formatDate(currentActivity.signupEndTime) }}</span>
          </div>
          <div class="detail-item">
            <label>活动容量：</label>
            <span>{{ currentActivity.capacity }}人</span>
          </div>
          <div class="detail-item">
            <label>当前报名人数：</label>
            <span>{{ currentActivity.currentParticipants || 0 }}人</span>
          </div>
          <div class="detail-item">
            <label>创建时间：</label>
            <span>{{ formatDateTime(currentActivity.createTime) }}</span>
          </div>
          <div class="detail-item">
            <label>修改时间：</label>
            <span>{{ formatDateTime(currentActivity.updateTime) }}</span>
          </div>
        </div>
        
        <div class="detail-item full-width">
          <label>活动详情：</label>
          <div class="activity-content">
            {{ currentActivity.activityDetail }}
          </div>
        </div>

        <div v-if="currentActivity.image" class="detail-item full-width">
          <label>活动图片：</label>
          <div class="activity-image">
            <el-image
              :src="currentActivity.image"
              :preview-src-list="[currentActivity.image]"
              fit="cover"
              style="width: 200px; height: 150px; border-radius: 8px;"
            />
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 新增/编辑活动对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑活动' : '新增活动'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="activityFormRef"
        :model="activityForm"
        :rules="activityRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动名称" prop="name">
              <el-input v-model="activityForm.name" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动地点" prop="location">
              <el-input v-model="activityForm.location" placeholder="请输入活动地点" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动开始时间" prop="activityStartTime">
              <el-date-picker
                v-model="activityForm.activityStartTime"
                type="date"
                placeholder="选择开始日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动结束时间" prop="activityEndTime">
              <el-date-picker
                v-model="activityForm.activityEndTime"
                type="date"
                placeholder="选择结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报名开始时间" prop="signupStartTime">
              <el-date-picker
                v-model="activityForm.signupStartTime"
                type="date"
                placeholder="选择报名开始日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报名截止时间" prop="signupEndTime">
              <el-date-picker
                v-model="activityForm.signupEndTime"
                type="date"
                placeholder="选择报名截止日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动容量" prop="capacity">
              <el-input-number
                v-model="activityForm.capacity"
                :min="1"
                :max="10000"
                placeholder="请输入活动容量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动状态" prop="status">
              <el-select v-model="activityForm.status" placeholder="请选择活动状态" style="width: 100%">
                <el-option label="未开始" :value="1" />
                <el-option label="报名中" :value="2" />
                <el-option label="进行中" :value="3" />
                <el-option label="已结束" :value="4" />
                <el-option label="已取消" :value="5" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="活动图片" prop="image">
          <div class="image-upload-container">
            <!-- 图片上传组件 -->
            <el-upload
              class="image-uploader"
              :action="''"
              :http-request="handleImageUpload"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <div v-if="activityForm.image" class="image-preview">
                <el-image
                  :src="activityForm.image"
                  fit="cover"
                  style="width: 150px; height: 100px; border-radius: 6px;"
                />
                <div class="image-overlay">
                  <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    circle
                    @click.stop="removeImage"
                  />
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon class="upload-icon" v-if="!uploadLoading">
                  <Plus />
                </el-icon>
                <el-icon class="upload-icon is-loading" v-else>
                  <Loading />
                </el-icon>
                <div class="upload-text">{{ uploadLoading ? '上传中...' : '点击上传图片' }}</div>
              </div>
            </el-upload>
            
            <!-- 手动输入URL选项 -->
            <div class="url-input-section">
              <el-divider>或</el-divider>
              <el-input
                v-model="activityForm.image"
                placeholder="也可以直接输入图片URL"
                clearable
              >
                <template #prepend>图片URL</template>
              </el-input>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="活动详情" prop="activityDetail">
          <el-input
            v-model="activityForm.activityDetail"
            type="textarea"
            :rows="4"
            placeholder="请输入活动详情描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  View,
  Edit,
  Delete,
  Loading
} from '@element-plus/icons-vue'
import { queryActivityList, findActivity, addActivity, updateActivity, deleteActivity, uploadImage,updateActivityStatus } from '@/api/school'

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const statusLoading = ref(false)
const activityList = ref([])
const viewDialogVisible = ref(false)
const editDialogVisible = ref(false)
const isEdit = ref(false)
const currentActivity = ref(null)
const activityFormRef = ref()
const uploadLoading = ref(false)

// 表格高度计算
const tableHeight = computed(() => {
  // 基础高度：页面高度 - 标题 - 搜索区域 - 分页器 - 各种间距
  // 这里设置一个合适的固定高度，确保表格能够显示滚动条
  return 'calc(100vh - 320px)'
})

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  limit: 5,
  total: 0
})

// 活动表单
const activityForm = reactive({
  id: null,
  name: '', // 表单中仍使用name，提交时会转换
  location: '',
  activityStartTime: '',
  activityEndTime: '',
  signupStartTime: '',
  signupEndTime: '',
  capacity: null,
  status: 1,
  image: '',
  activityDetail: ''
})

// 表单验证规则
const activityRules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  activityStartTime: [
    { required: true, message: '请选择活动开始时间', trigger: 'change' }
  ],
  activityEndTime: [
    { required: true, message: '请选择活动结束时间', trigger: 'change' }
  ],
  signupStartTime: [
    { required: true, message: '请选择报名开始时间', trigger: 'change' }
  ],
  signupEndTime: [
    { required: true, message: '请选择报名截止时间', trigger: 'change' }
  ],
  capacity: [
    { required: true, message: '请输入活动容量', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择活动状态', trigger: 'change' }
  ]
}

// 获取活动列表
const getActivityList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      name: searchForm.name || undefined
    }
    
    const response = await queryActivityList(params)
    if (response && response.code === 0) {
      // 对列表数据进行字段映射处理
      activityList.value = (response.data || []).map(item => ({
        ...item,
        // 活动名称：优先使用aname，如果为空则使用activityDetail作为备选
        aname: item.aname || item.name || item.activityDetail || '未知活动',
        // 发布人：直接使用后端返回的ename字段
        ename: item.ename || item.employeename || item.employeeName || item.publisher || item.creator || '未知发布人'
      }))
      
      pagination.total = response.count || 0
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getActivityList()
}

// 重置搜索
const handleReset = () => {
  searchForm.name = ''
  pagination.page = 1
  getActivityList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.limit = size
  pagination.page = 1
  getActivityList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  getActivityList()
}

// 一键更新活动状态
const handleUpdateStatus = async () => {
  ElMessageBox.confirm(
      '此操作将根据当前时间自动更新所有活动的状态，是否继续？',
      '确认更新',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    statusLoading.value = true
    try {
      const res = await updateActivityStatus()
      if (res.code === 0 || res.code === 200) {
        ElMessage.success(res.data || '活动状态更新成功')
        // 刷新列表
        getActivityList()
      } else {
        ElMessage.error(res.msg || '活动状态更新失败')
      }
    } catch (error) {
      console.error('更新活动状态失败:', error)
      ElMessage.error('更新失败，请稍后重试')
    } finally {
      statusLoading.value = false
    }
  }).catch(() => {
    // 取消操作
  })
}

// 查看活动详情
const handleView = async (row) => {
  try {
    const response = await findActivity(row.id)
    if (response && response.code === 0) {
      const data = response.data
      
      // 兼容性处理：如果后端返回的是旧字段名，进行映射
      currentActivity.value = {
        ...data,
        // 活动名称：优先使用aname，如果为空则使用activityDetail作为备选
        aname: data.aname || data.name || data.activityDetail || '未知活动',
        // 发布人：直接使用后端返回的ename字段
        ename: data.ename || data.employeename || data.employeeName || data.publisher || data.creator || '未知发布人'
      }
      viewDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取活动详情失败:', error)
    ElMessage.error('获取活动详情失败')
  }
}

// 新增活动
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  editDialogVisible.value = true
}

// 编辑活动
const handleEdit = async (row) => {
  try {
    const response = await findActivity(row.id)
    if (response && response.code === 0) {
      isEdit.value = true
      const data = response.data
      // 映射后端字段到表单字段
      Object.assign(activityForm, {
        ...data,
        // 活动名称：优先使用aname，如果为空则使用activityDetail作为备选
        name: data.aname || data.name || data.activityDetail || ''
      })
      // 转换日期格式
      if (activityForm.activityStartTime) {
        activityForm.activityStartTime = new Date(activityForm.activityStartTime)
      }
      if (activityForm.activityEndTime) {
        activityForm.activityEndTime = new Date(activityForm.activityEndTime)
      }
      if (activityForm.signupStartTime) {
        activityForm.signupStartTime = new Date(activityForm.signupStartTime)
      }
      if (activityForm.signupEndTime) {
        activityForm.signupEndTime = new Date(activityForm.signupEndTime)
      }
      editDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取活动信息失败:', error)
    ElMessage.error('获取活动信息失败')
  }
}

// 删除活动
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除活动"${row.aname}"吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteActivity(row.id)
      if (response && response.code === 0) {
        ElMessage.success('删除成功')
        getActivityList()
      }
    } catch (error) {
      console.error('删除活动失败:', error)
      ElMessage.error('删除活动失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 保存活动
const handleSave = () => {
  activityFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        saveLoading.value = true
        const formData = { ...activityForm }
        
        // 表单字段name直接发送给后端，不需要映射为aname
        // formData.name 保持不变，后端期望接收name字段
        
        // 转换日期格式
        if (formData.activityStartTime) {
          formData.activityStartTime = formatDateForSubmit(formData.activityStartTime)
        }
        if (formData.activityEndTime) {
          formData.activityEndTime = formatDateForSubmit(formData.activityEndTime)
        }
        if (formData.signupStartTime) {
          formData.signupStartTime = formatDateForSubmit(formData.signupStartTime)
        }
        if (formData.signupEndTime) {
          formData.signupEndTime = formatDateForSubmit(formData.signupEndTime)
        }

        let response
        if (isEdit.value) {
          response = await updateActivity(formData)
        } else {
          delete formData.id
          response = await addActivity(formData)
        }

        if (response && response.code === 0) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          editDialogVisible.value = false
          getActivityList()
        }
      } catch (error) {
        console.error('保存活动失败:', error)
        ElMessage.error('保存活动失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 图片上传前的验证
const beforeImageUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 自定义图片上传处理
const handleImageUpload = async (options) => {
  const { file } = options
  
  try {
    uploadLoading.value = true
    const response = await uploadImage(file)
    
    if (response && response.code === 0) {
      activityForm.image = response.data
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(response?.msg || '图片上传失败')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  } finally {
    uploadLoading.value = false
  }
}

// 移除图片
const removeImage = () => {
  activityForm.image = ''
}

// 重置表单
const resetForm = () => {
  Object.assign(activityForm, {
    id: null,
    name: '',
    location: '',
    activityStartTime: '',
    activityEndTime: '',
    signupStartTime: '',
    signupEndTime: '',
    capacity: null,
    status: 1,
    image: '',
    activityDetail: ''
  })
  if (activityFormRef.value) {
    activityFormRef.value.resetFields()
  }
}

// 格式化日期显示
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 格式化日期时间显示
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  
  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) return dateTimeStr
    
    const now = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    
    // 如果是今年，不显示年份
    if (year === now.getFullYear()) {
      return `${month}-${day} ${hours}:${minutes}`
    }
    
    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('时间格式化错误:', error)
    return dateTimeStr
  }
}

// 格式化相对时间显示
const formatRelativeTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  
  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) return dateTimeStr
    
    const now = new Date()
    const diffMs = now.getTime() - date.getTime()
    const diffSeconds = Math.floor(diffMs / 1000)
    const diffMinutes = Math.floor(diffSeconds / 60)
    const diffHours = Math.floor(diffMinutes / 60)
    
    // 未来时间显示为具体时间
    if (diffMs < 0) {
      return '未来时间'
    }
    
    // 今天的时间
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const dateOnly = new Date(date)
    dateOnly.setHours(0, 0, 0, 0)
    const daysDiff = Math.floor((today.getTime() - dateOnly.getTime()) / (1000 * 60 * 60 * 24))
    
    // 相对时间显示
    if (daysDiff === 0) {
      // 今天
      if (diffSeconds < 60) {
        return '刚刚'
      } else if (diffMinutes < 60) {
        return `${diffMinutes}分钟前`
      } else {
        return `${diffHours}小时前`
      }
    } else if (daysDiff === 1) {
      return '昨天'
    } else if (daysDiff === 2) {
      return '前天'
    } else if (daysDiff < 7) {
      return `${daysDiff}天前`
    } else if (daysDiff < 30) {
      const weeks = Math.floor(daysDiff / 7)
      return `${weeks}周前`
    } else if (daysDiff < 365) {
      const months = Math.floor(daysDiff / 30)
      return `${months}个月前`
    } else {
      const years = Math.floor(daysDiff / 365)
      return `${years}年前`
    }
  } catch (error) {
    console.error('相对时间格式化错误:', error)
    return formatDateTime(dateTimeStr)
  }
}

// 格式化日期用于提交
const formatDateForSubmit = (date) => {
  if (!date) return null
  const d = new Date(date)
  return d.getFullYear() + '-' + 
         String(d.getMonth() + 1).padStart(2, '0') + '-' + 
         String(d.getDate()).padStart(2, '0')
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    1: 'info',     // 未开始
    2: 'success',  // 报名中
    3: 'warning',  // 进行中
    4: '',         // 已结束
    5: 'danger'    // 已取消
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '未开始',
    2: '报名中',
    3: '进行中',
    4: '已结束',
    5: '已取消'
  }
  return statusMap[status] || '未知'
}

// 页面加载时获取数据
onMounted(() => {
  getActivityList()
})
</script>

<style scoped>
.activity-manage {
  padding: 5px 20px 5px 20px; /* 减少上下padding */
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px); /* 减少高度限制 */
  max-height: calc(100vh - 60px); /* 减少最大高度 */
  overflow-y: auto; /* 垂直方向自动显示滚动条 */
  overflow-x: hidden; /* 隐藏水平滚动条 */
  display: flex;
  flex-direction: column;
  
  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

/* Webkit浏览器滚动条样式 */
.activity-manage::-webkit-scrollbar {
  width: 8px;
}

.activity-manage::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.activity-manage::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.activity-manage::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

.page-header {
  margin-bottom: 8px; /* 减少页面标题的底部间距 */
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.search-card {
  margin-bottom: 8px; /* 减少搜索卡片的底部间距 */
}

.table-card {
  background-color: #fff;
  margin-bottom: 10px; /* 减少底部间距 */
  flex: 1; /* 让表格卡片占据剩余空间 */
  display: flex;
  flex-direction: column;
  min-height: 0; /* 允许flex子元素缩小 */
  overflow: hidden; /* 防止内容溢出 */
}

.table-wrapper {
  flex: 1;
  overflow: hidden;
}

.activity-name {
  display: flex;
  flex-direction: column;
}

.activity-title {
  font-weight: 600;
  margin-bottom: 4px;
}

.participant-info {
  font-weight: 600;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px; /* 减少顶部间距 */
  margin-bottom: 10px; /* 减少底部边距 */
  padding: 10px 20px; /* 调整内边距 */
  flex-shrink: 0; /* 防止分页器被压缩 */
  background-color: #fff; /* 确保分页器背景为白色 */
}

.activity-detail {
  padding: 16px 0;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 24px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
}

.detail-item.full-width {
  grid-column: 1 / -1;
  flex-direction: column;
}

.detail-item label {
  font-weight: 600;
  color: #606266;
  min-width: 120px;
  margin-right: 12px;
}

.detail-item.full-width label {
  margin-bottom: 8px;
}

.activity-content {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  line-height: 1.6;
  white-space: pre-wrap;
}

.activity-image {
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}


/* 时间显示样式 */
.time-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.relative-time {
  font-weight: 500;
  color: #409eff;
  font-size: 13px;
  cursor: help;
}

.exact-time {
  font-size: 11px;
  color: #909399;
  line-height: 1.2;
}

/* 响应式优化 */
@media screen and (max-width: 768px) {
  .activity-manage {
    padding: 5px 15px 5px 15px; /* 移动端减少padding */
    max-height: calc(100vh - 50px); /* 移动端调整最大高度 */
  }
  
  .pagination-container {
    justify-content: center; /* 移动端居中显示分页器 */
    margin-bottom: 8px; /* 移动端减少底部边距 */
    padding: 10px 15px;
  }
  
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
  
  .time-display {
    gap: 1px;
  }
  
  .relative-time {
    font-size: 12px;
  }
  
  .exact-time {
    font-size: 10px;
  }
}

/* 图片上传组件样式 */
.image-upload-container {
  width: 100%;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 150px;
  height: 100px;
}

.image-uploader:hover {
  border-color: #409eff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #fafafa;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-icon.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.upload-text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.image-preview {
  position: relative;
  width: 100%;
  height: 100%;
}

.image-overlay {
  position: absolute;
  top: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 0 6px 0 6px;
  padding: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview:hover .image-overlay {
  opacity: 1;
}

.url-input-section {
  margin-top: 16px;
}

</style>